package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.dao.MenuMapper;
import com.itheima.dao.RoleMapper;
import com.itheima.pojo.Menu;
import com.itheima.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;

/**
 * 菜单接口实现
 * @author HY
 * @version 2/11/2020
 */
@Service(interfaceClass = MenuService.class)
@Transactional
public class MenuServiceImpl implements MenuService {
    @Autowired
    MenuMapper menuMapper;
    @Autowired
    RoleMapper roleMapper;

    /**
     * 获取全部菜单(树形)
     * @return 树形菜单对象
     */
    @Override
    public List<Menu> getMenus() {
        List<Menu> menus = menuMapper.queryAll();
        return menus;
    }

    /**
     * 添加菜单
     * @param menu Menu 对象
     */
    @Override
    public void addMenu(Menu menu) {
        menuMapper.addMenu(menu);
    }

    /**
     * 编辑菜单
     * @param menu Menu 对象
     */
    @Override
    public void editMenu(Menu menu) {
        menuMapper.editMenu(menu);
    }

    /**
     * 删除菜单
     * @param id 菜单id
     */
    @Override
    public void deleteMenu(Integer id) {
        menuMapper.deleteMenu(id);
    }

    /**
     * 根据用户id查询该用户权限内的所有menu
     * @param id
     * @return 一级菜单list
     */
    @Override
    public List<Menu> getUserMenu(Integer id) {
        List<Menu> menuList = menuMapper.getAllMenuByUserId(id);
        LinkedList<Menu> list1 = new LinkedList<>();
        //将所有一级菜单添加到list1中
        for (Menu menu : menuList) {
            if(menu.getParentMenuId() == null){list1.add(menu);}
        }
        //删除menuList中包含的list1元素
        for (Menu menu : list1) {
          menuList.remove(menu);
        }
        return getChildren(menuList,list1,menuList.size());
    }

    /**
     * 根据所有menu的list集合，和一级菜单的list集合，递归给所有一级菜单中的children赋值
     * @param totalMenu 所有menu的list集合，包含一级二级等menu
     * @param firstMenu 一级菜单list
     * @param totalCount 包含所有menu的list的大小
     * @return
     */
    private List<Menu> getChildren(List<Menu> totalMenu, List<Menu> firstMenu,int totalCount) {
        if (totalCount != 0) {
            for (Menu menu : firstMenu) {
                List<Menu> children1 = getChild(totalMenu, menu.getId());
                menu.setChildren(children1);
                totalCount = totalCount-1;
                getChildren(totalMenu, children1,totalCount);
            }
        }
        return firstMenu;
    }

    /**
     *
     * @param menuList 所有menu的list集合
     * @param id 父级菜单的id
     * @return
     */
    private List<Menu> getChild(List<Menu> menuList, int id) {
        LinkedList<Menu> menus = new LinkedList<>();
        for (Menu menu : menuList) {
            if (menu.getParentMenuId() == id) {
                menus.add(menu);
            }
        }
        return menus;
    }
}
